<?php

declare (strict_types=1);

namespace app\services;



use app\services\BaseServices;
use app\traits\ServicesTrait;


use think\exception\ValidateException;
use think\facade\Cache;
//use think\facade\Db;


use support\Container;


use Exception;



/**
 *
 * Class CaptchaServices
 * @package app\services
 */
class CaptchaServices extends BaseServices
{
    use ServicesTrait;
    
    /**
     * CaptchaServices constructor.
     */
    public function __construct()
    {
        //$this->dao = Container::get(SystemLogDao::class);
        //$this->dao = new SystemLogDao;
    }


    
    //创建验证码
    public function createCaptcha()
    {
		$config = config('lms_common');

        $c = new \plugin\think\captcha\Captcha;
        
        $captcha = $c->create();
        //echo $captcha['value'] . PHP_EOL;
		$hash = session_create_id();
        ////$hash = password_hash($key, PASSWORD_BCRYPT, ['cost' => 10]);

        Cache::store('redis')->set($config['captcha']['prefix'] . $hash, $captcha['value'], $config['captcha']['expire']);

		return ['key' => $hash, 'img' => base64_encode($captcha['img'])];
        //return '<img src="data:image/png;base64,' . base64_encode($captcha['img']) . '">';
        //return response($content, 200, ['Content-Length' => strlen($content)])->contentType('image/png');
    }
	
    //验证，成功后会删除
    public function verifyCaptcha($code, $key): bool
    {
        /*echo Cache::store('redis')->get($config['captcha']['prefix'] . $k);
    	*/
        if(is_null($code))
            return false;


		$config = config('lms_common');
		$res = false;

		//缓存中没有
		if (!Cache::store('redis')->has($config['captcha']['prefix'] . $key)) {
			$res = false;
		}
		else
		{
			$value = Cache::store('redis')->get($config['captcha']['prefix'] . $key);
	
			//$code = ;
	
			//$res = password_verify($code, $key);
			$res = ( mb_strtolower($code, 'UTF-8') === $value);
		}

		//if ($res) {
			Cache::store('redis')->delete('captcha_' . $key);
		//}
		
		
		return $res;
    }

}